<?php

namespace app\api\controller;

use app\activity\logic\activityLogic;
use app\cassification\logic\ClassificationDictionaryLogic;
use app\dataDashboard\logic\dataDashboardLogic;
use app\JumpConfig\logic\JumpConfigLogic;
use app\parkDisplayMap\logic\parkDisplayMapLogic;
use app\policy\logic\PolicyLogic;
use app\privacyPolicy\logic\privacyPolicyLogic;
use app\recruitment\logic\recruitmentLogic;
use app\space\logic\spaceLogic;
use app\supplyDemand\logic\supplyDemandLogic;
use app\userAgreement\logic\userAgreementLogic;
use plugin\saiadmin\app\logic\system\SystemConfigLogic;
use plugin\saiadmin\basic\OpenController;
use app\api\annotation\LoginRequired;
use plugin\saiadmin\utils\Arr;
use support\Request;
use app\api\basic\BaseController;
use think\facade\Db;

class IndexController extends OpenController {
     protected $userInfo;

    /**
     * 当前登陆管理员ID
     */
    protected $userId;

    /**
     * 当前登陆管理员账号
     */
    protected $userName;
    public function __construct()
    {   
        parent::__construct();
        $this->userId=request()->userId;
        $this->userName=request()->userName;
        $this->userInfo=request()->userInfo;
    }
   
    #[LoginRequired(required:false)]
    public function index(Request $request) {
        $param = $request->more([
            ['lang_code','zh']
        ]);
        //
        $policy=new PolicyLogic();
        $policyData=$policy->search($param)
        ->field('policy_id,policy_title')
        ->where('policy_category',23)
        ->where('is_top',1)
        ->whereNull('delete_time')
        ->order('sort_order desc')
            ->order('create_time desc')
        ->select();
        //值得关注
        $activity=new  activityLogic();
        $activityData=$activity->search($param)
        ->field('activity_id,activity_title,activity_cover,create_time')
        ->where('is_display',1)
        ->whereNull('delete_time')
        ->order('sort_order desc')
            ->order('create_time desc')
        ->limit(4)->select()
        ->toArray();
        //供求大厅
       // $ebSupplyDemand=new supplyDemandLogic();
//        $supplyDemandData['recommend']=$ebSupplyDemand->search($param)
//        //->where('is_recommend',1)
//        ->field('sd_id,product_name,product_subtitle,image,supply_demand,enterprise_id')
//            ->order('sort_order desc')
//        ->order('create_time desc')
//        ->limit(4)->select()
//        ->toArray();
//        $supplyDemandData['supply']=$ebSupplyDemand->search($param)
//        ->where('supply_demand',19)
//        ->field('sd_id,product_name,product_subtitle,image,supply_demand,enterprise_id')
//            ->order('sort_order desc')
//        ->order('create_time desc')
//        ->limit(4)->select()
//        ->toArray();
//        $supplyDemandData['demand']=$ebSupplyDemand->search($param)
//        ->where('supply_demand',20)
//        ->field('sd_id,product_name,product_subtitle,image,supply_demand,enterprise_id')
//            ->order('sort_order desc')
//        ->order('create_time desc')
//        ->limit(4)->select()
//        ->toArray();
        $user_id =$this->userId;
        $type =1;

        $supplyDemandData['recommend'] =productRole($user_id,$type,0,0,[]);
        //获取供需



        //人力招聘
        $recruitment=new recruitmentLogic();
        $recruitmentData=$recruitment->search($param)->where('is_display',1)
        ->whereNull('delete_time')
        ->order('sort_order desc')
        ->order('create_time desc')
        ->limit(2)->select()
        ->toArray();
        //找厂房
        $space=new spaceLogic();
        $spaceData=$space->search($param)
        ->field('space_id,space_title,space_image,rent_nature,rent_price,building_area,address,create_time')
        ->whereNull('delete_time')
        ->order('sort_order desc')
        ->order('create_time desc')
        ->limit(2)->select()
        ->toArray();
        //AI是否开启
            $logic = new SystemConfigLogic();
            $sharConfig = $logic->getGroup('ai_config');
            $ai_type=Arr::getConfigValue($sharConfig,'type');
            $setting = [
                'ai_type' =>$ai_type,
            ];

            return $this->success([
                 'policyData'=>$policyData,
                 'activityData' => $activityData,
                'supplyDemandData' => $supplyDemandData,
                'recruitmentData' => $recruitmentData,
                'spaceData' => $spaceData,
                 'setting'  =>$setting
            ]);

        }
    /**
     * 获取分类列表
     */
    #[LoginRequired(required:false)]
    public function getClassification(Request $request){
        $param = $request->more([
            ['lang_code','zh'],
            ['classification_type',1],
        ]);
        $check=['zh','en','ja','ko'];
        if(!in_array($param['lang_code'],$check)){
            return $this->fail('语言代码失效');
        }
        $classification_name='classification_name_'.$param['lang_code'];
        $spaceClass=new ClassificationDictionaryLogic();
       
        $spaceClassData=$spaceClass->search(['classification_type'=>$param['classification_type']])
        ->field("dictionary_id as value,{$classification_name} as label,classification_name_zh")
        ->whereNull('delete_time')
        ->order('sort_order desc')
        ->order('create_time desc')
        ->select()
        ->toArray();
         $data=[];
         foreach($spaceClassData as $key=>$item){
            $data[$key]['value']=$item['value'];
            $data[$key]['label']=empty($item['label'])?$item['classification_name_zh']:$item['label'];
         }
        
        return $this->success($data);
    }
    #[LoginRequired(required:false)]
    public function agreement(Request $request){
        $param = $request->more([
            ['lang_code','zh'],
            ['type',1]
        ]);
        $check=['zh','en','ja','ko'];
        if(!in_array($param['lang_code'],$check)){
            return $this->fail('语言代码失效');
        }
        $userAgreementLogic=new userAgreementLogic();
        $privacyPolicyLogic=new privacyPolicyLogic();
        if($param['type']==1){
            $data=$userAgreementLogic->where('lang_code',$param['lang_code'])->field('content')->find();
        }else{
            $data=$privacyPolicyLogic->where('lang_code',$param['lang_code'])->field('content')->find();
        }
        if($data) $data=$data->toArray();
        return $this->success($data);
    }
    //服务入口
    #[LoginRequired(required:false)]
    public function getJumpConfig(Request $request){
        $param=$request->more([
            ['lang_code','zh'],
            ['page',1],
            ['limit',10]
        ]);
         $check=['zh','en','ja','ko'];
        if(!in_array($param['lang_code'],$check)){
            return $this->fail('语言代码失效');
        }
        $jumpConfigLogic=new JumpConfigLogic();
        $name='name_'.$param['lang_code'];
        $data=$jumpConfigLogic->field("{$name} as title,icon,appid,path")->paginate($param['limit']);
        
        return $this->success(['data'=>$data->items(),'total'=>$data->total()]);
    }
    //数据大屏   /
    #[LoginRequired(required:false)]
    public function  dataDashboard(Request $request){
        $dataDashboardLogic= new dataDashboardLogic();
        $dataInfo =$dataDashboardLogic->where(['id'=>1])->find();
        $parkDisplayMapLogic = new parkDisplayMapLogic();
        $map = $parkDisplayMapLogic->select();
        $resulte['dataDashboard']= $dataInfo;
        $resulte['parkDisplay']= $map;
        return $this->success(['data'=>$resulte]);
    }


    //小程序分享图片接口
    #[LoginRequired(required:false)]
    public function shaer(Request $request){
        $logic = new SystemConfigLogic();
        $sharConfig = $logic->getGroup('shar_config');

        $wechatConfig = $logic->getGroup('map_config');
        $data['mapKey']=Arr::getConfigValue($wechatConfig,'mapKey');
        $data['title']=Arr::getConfigValue($sharConfig,'title');
        $data['shaer']=Arr::getConfigValue($sharConfig,'shaer');
        return $this->success(['data' =>$data]);
    }

    public function run($model = "ernie-4.5-turbo-128k", $userMessage = "你好") {
        $logic = new SystemConfigLogic();
        $wechatConfig = $logic->getGroup('ai_config');
        $appId=Arr::getConfigValue($wechatConfig,'appid');
        $appkey=Arr::getConfigValue($wechatConfig,'appkey');
        $curl = curl_init();

        // 构建请求数据
        $data = [
            "model" => $model,
            "messages" => [
                [
                    "role" => "user",
                    "content" => [
                        [
                            "type" => "text",
                            "text" => $userMessage
                        ]
                    ]
                ]
            ],
            "web_search" => [
                "enable" => false,
                "enable_citation" => false,
                "enable_trace" => false
            ],
            // 修正：确保plugin_options被序列化为空对象{}
            "plugin_options" => (object)[]
        ];

        // 调试：打印请求数据，确认JSON格式
        $jsonData = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        error_log("AI参数-Data: " . $jsonData);

        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://qianfan.baidubce.com/v2/chat/completions",
            CURLOPT_TIMEOUT => 240,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $jsonData,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Authorization: Bearer '.$appkey,
                'appid:'.$appId
            ),
        ));

        $response = curl_exec($curl);
        $error = curl_error($curl);
        curl_close($curl);

        if ($error) {
            return "cURL Error: " . $error;
        }

        // 调试：打印响应数据
file_put_contents('AI.txt',$response);
        return $response;
    }
    #[LoginRequired(required:false)]
    public function ceshi(Request $request) {
        $param = $request->more([
            ['question', ''],
        ]);

        // 检查输入参数
        if (empty($param['question'])) {
            return $this->fail('问题不能为空');
        }

        $rtn = $this->run("ernie-4.5-turbo-128k", $param['question']);

        // 尝试解析JSON响应
        $responseData = json_decode($rtn, true);

        // 如果解析成功且包含错误信息
        if (json_last_error() === JSON_ERROR_NONE && isset($responseData['error'])) {
            return $this->error('API错误: ' . $responseData['error']['message']);
        }
        $data = json_decode($rtn,true);
        file_put_contents('AIqu1.txt',json_encode($data['choices'],JSON_UNESCAPED_UNICODE));
        file_put_contents('AIqu2.txt',json_encode($data['choices'][0],JSON_UNESCAPED_UNICODE));
        file_put_contents('AIqu.txt',json_encode($data['choices'][0]['message'],JSON_UNESCAPED_UNICODE));
        return $this->success(['data' => $data['choices'][0]['message']]);
    }

    #[LoginRequired(required:false)]
    public function searchadd(Request $request) {
        $param = $request->more([
            ['keyword', ''],
        ]);
        $param['user_id']=$this->userId;
        // 检查输入参数
        if (!empty($param['user_id']) || !empty($param['keyword'])) {
            $table = 'eb_search_history';
            $userId = $param['user_id'];
            $keyword = $param['keyword'];

            // 检查当前用户的搜索记录数量
            $count = Db::table($table)->where(['user_id' => $userId])->count();

            // 如果超过20条，删除最早的一条记录
            if ($count >= 20) {
                // 获取最早的记录ID
                $oldestId = Db::table($table)
                    ->where(['user_id' => $userId])
                    ->orderBy('id', 'asc') // 按ID升序，取第一条就是最早的
                    ->value('id');

                // 删除最早的记录
                if ($oldestId) {
                    Db::table($table)->where('id', $oldestId)->delete();
                }
            }
            $keywordcount = Db::table($table)->where(['user_id' => $userId, 'keyword' => $keyword])->count();
            if ($keywordcount == 0) {
                // 添加新的搜索记录，包含时间戳便于后续排序
                Db::table($table)->insert([
                    'user_id' => $userId,
                    'keyword' => $keyword,
                ]);
            }
        }
        return $this->success('操作成功');
    }
    #[LoginRequired(required:false)]
    public function searchalist(Request $request) {
        $param['user_id']=$this->userId;
        // 检查输入参数
        if (empty($param['user_id'])) {
            return $this->success(['data'=>[]]);
        }
        $table = 'eb_search_history';
        $userId = $param['user_id'];
        $resut = Db::table($table)->where(['user_id' => $userId])->select();

        return $this->success(['data'=>$resut]);
    }

    //删除全部
    #[LoginRequired(required:false)]
    public function  delAll(){
        $param['user_id']=$this->userId;
        if (!empty($param['user_id'])) {
            $table = 'eb_search_history';
            $userId = $param['user_id'];
            $resut = Db::table($table)->where(['user_id' => $userId])->delete();

        }
        return $this->success('操作成功');
    }

    #[LoginRequired(required:false)]
    public function isLogin(Request $request) {
        $user_id = $this->userId;
        if($user_id){
            $login = true;
        }else{
            $login = false;
        }
        return $this->success(['data'=>$login]);

    }

}
